<!--课程与题库-在线课程-编辑直播课-->
<template>
  <div class="form-container">
    <el-card class="box-card">
      <div class="card-header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/banner/index'}">banner管理</el-breadcrumb-item>
          <el-breadcrumb-item>banner编辑</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form"  ref="baseForm" label-width="120px">
        <div class="head-card">
          <!-- 展示位置 -->
          <el-form-item label="展示位置：" prop="qyxx_type">
            <el-select
              v-model="form.bannerWeizhi"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in weizhi"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 展示排序 -->
          <el-form-item label="展示排序：" prop="qyxx_type">
            <el-select
              v-model="form.bannerOrderBy"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in orderBy"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- banner -->
          <el-form-item label="banner：">
             <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :on-change="changeBanner"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseBanner" :src="courseBanner" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="upload-tip">展示于主要列表。图片小于2M。
              建议上传 5:2 比例（如800x320px）的JPG/PNG/WebP格式。</div>
          </el-form-item>

          <!-- 跳转链接 -->
          <el-form-item label="跳转链接：" prop="user_phoneno" >
            <el-input
              v-model="form.bannerUrl"
              placeholder="请输入"
              clearable
              type="textarea"
              rows="2"
            ></el-input>
          </el-form-item>
        </div>
        <!--表单操作 -->
        <el-form-item>
          <el-button type="primary" :disabled="isButtonDisabled" @click="saveBanner()">保存</el-button>
          <el-button type="primary" @click="saveLiveCourse('1')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  uploadres,
  updatecbzbstate,
  createbanner, updatebanner
} from "../../api/InstitutionApi";

export default {
  data() {
    return {
      form: {
        bbncode: '', ///banner的code
        bannerWeizhi:'', ///展示位置
        bannerOrderBy:'', ///展示排序
        apiImgBannerCode: '', ////存储banner的Code
        bannerUrl: '', ///跳转链接
        banneruri: '',
        px: ''
      },
      courseBanner: '', ///banner的baser64a或链接
      base64Data: '',
      // 弹窗存储
      unReview:'',
      // 题库
      teacherList: [],
      // 专展示位置
      weizhi: [
        { value: '1', label: '企业机构端-人才招聘页' },
        { value: '2', label: '从业者端-在线学习页' },
      ],
      orderBy: [
        { value: '1', label: '未发布' },
        { value: '2', label: '1' },
        { value: '3', label: '2' },
        { value: '4', label: '3' },
        { value: '5', label: '4' },
        { value: '6', label: '5' },
      ],
      // 直播课编辑内容
      bannerrow: {},
      isEdit: false,
    }
  },
  created() {
    // 直播编辑传数据
    this.bannerrow = this.$route.query.bannerrow
    console.log('编辑直播：',this.bannerrow)
    if (this.bannerrow) {
      this.isEdit = true
      this.bannerEdit()
    } else {
      this.isEdit = false
    }
  },
  computed: {
    isButtonDisabled() {
      // return this.form.base.cur_status === 2; // 可以扩展其他条件，如 || this.isLoading
    }
  },
  methods: {
    // 编辑banner
    bannerEdit() {
      this.form.bbncode = this.bannerrow.bbn_code
      this.form.bannerWeizhi = this.bannerrow.bbn_wz ///展示位置
      this.form.bannerOrderBy = this.bannerrow.bbn_pxname === '未发布' ? this.bannerrow.bbn_pxname : this.bannerrow.bbn_pxname.slice(-1) //展示排序
      this.courseBanner= this.bannerrow.bbn_imguri[0].url//#直播banner
      this.form.apiImgBannerCode = this.bannerrow.bbn_imguri[0].imguri ///banner的code
      this.form.bannerUrl= this.bannerrow.bbn_desc //#链接
      this.form.px = this.bannerrow.bbn_px ////排序
    },
    disabled() {
      return disabled
    },
    // 保存
    saveBanner() {
      this.form.px = this.form.bannerOrderBy === '未发布' ? '0' :  this.form.bannerOrderBy
      if(this.isEdit) {
        //   编辑
        // this.form.bbnpxname = this.form.bannerOrderBy === '未发布' ? this.form.bannerOrderBy : '已发布'+this.form.bannerOrderBy
        updatebanner({
          "bbncode": this.form.bbncode, ///code
          "bbnwz":this.form.bannerWeizhi, ///位置
          "bbnpx": this.form.px, //#排序
          "bbnpxname": this.form.bannerOrderBy, ///展示排序
          "bbnimguri": this.form.apiImgBannerCode,//#直播banner
          "bbndesc": this.form.bannerUrl,//#链接
        }).then(res =>{
          console.log('编辑',res)
          if(res.msg === '更新banner成功') {
            this.$router.push({
              path: '/banner/index',
              query: ''
            });
          }
        })
      } else {
        console.log('bannerEdit', this.form)
        //   添加
        createbanner({
          "bbnwz": this.form.bannerWeizhi, //#直播名称
          "bbnpx": this.form.px,//#直播排名
          "bbnimguri": this.form.apiImgBannerCode,//#直播banner
          "bbndesc": this.form.bannerUrl,//#直播简介
        }).then(res => {
          console.log('创建banner：', res)
          if(res.msg === '创建banner成功') {
            this.$router.push({
              path: '/banner/index',
              query: ''
            });
          }
        })
      }
    },
    // 发布直播
    zbPublic() {
      updatecbzbstate({
        "bczbcode": this.form.courseCode, //#直播课的code
        "bczbstate":"1", //#直播课程状态，0未发布，1已发布，2已经结束
      }).then(res => {

      })
    },
    // 取消
    teacherCancel() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });

      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/teachers/teachers',
        query: ''
      });
    },

    // 头像
    // 头像上传
    // 自定义上传方法
    changeBanner(file) {
      console.log('banner：',file);
      this.beforeUpload(file.raw)
    },

    beforeUpload(file,type) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.courseBanner = reader.result;// 带前缀的完整Base64，可直接用于<img>显示
          // this.form.courseimgUrl = reader.result; // 带前缀的完整Base64，可直接用于<img>显示
          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload(type)
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },

    handleAvatarSuccess(res, file) {
      this.courseLogo = URL.createObjectURL(file.raw);
    },

    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    customUpload(type) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc": 'banner'  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.form.apiImgBannerCode = res.data.base_info
      })
    },

    //头像结束
  }
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
}

.head-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 30px;
}

.card-select {
  padding-left: 40px;
  font-size: 14px;
  margin-bottom: 30px;

}

.form-title {
  font-size: 18px;
  font-weight: bold;
}

.required-item >>> .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
